package com.hra.camera2demo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 申请权限的工具类，实现方法：
 * <p> checkAndApplyPermissions(),检查并申请权限;
 * <p> checkAuthorized(),检查是否已经授权，此方法仅在申请授权的类的onRequestPermissionsResult()方法中调用;
 */
@SuppressWarnings("all")
public class PermissionsUtil {

    /**
     * 权限检查与请求方法
     *
     * @param activity       上下文Activity
     * @param requestCode    请求标识码
     * @param permissionList 需要检查的权限数组
     * @return 是否已全部授权 (true=已授权，false=需要请求权限)
     */
    @SuppressLint("ObsoleteSdkInt")
    public static boolean checkAndRequestPermissions(@NonNull Activity activity, @NonNull String[] permissionList, int requestCode) {
        // 低版本直接返回已授权
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        // 使用LinkedHashSet保持顺序并去重
        Set<String> pendingPermissions = new LinkedHashSet<>();
        // 单次遍历检查权限
        for (String permission : permissionList) {
            if (ActivityCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                pendingPermissions.add(permission);
            }
        }
        // 无需要请求的权限
        if (pendingPermissions.isEmpty()) {
            return true;
        }
        // 转换数组并请求权限
        String[] permissionsToRequest = pendingPermissions.toArray(new String[0]);
        Log.d(activity.getClass().getSimpleName() + "Debug", "checkAndRequestPermissions: permissionsToRequest:" + permissionsToRequest);
        ActivityCompat.requestPermissions(activity, permissionsToRequest, requestCode);
        return false;
    }

    /**
     * 检查权限授予结果并处理未授权情况,在应用的启动类的onRequestPermissionsResult()方法中调用
     *
     * @param activity     上下文Activity
     * @param permissions  请求的权限数组
     * @param grantResults 授权结果数组
     * @return 是否全部权限已授权
     */
    public static boolean checkAuthorized(@NonNull Activity activity, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d(activity.getClass().getSimpleName() + "Debug", "checkAuthorized onRequestPermissionsResult: permissions:" + Arrays.toString(permissions)
                + ",grantResults:" + Arrays.toString(grantResults));
        boolean isNeedBuildPermissions = false;
        if (grantResults.length > 0) {
            for (int result : grantResults) {
                if (PackageManager.PERMISSION_GRANTED != result) {
                    isNeedBuildPermissions = true;
                    break;
                }
            }
        }
        if (isNeedBuildPermissions) {
            AlertDialog mAlertDialog = new AlertDialog.Builder(activity)
                    .setTitle("应用缺少运行所需要的权限！")
                    .setPositiveButton("关闭", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            activity.finish();
                        }
                    }).create();
            // 不能取消弹窗
            mAlertDialog.setCancelable(false);
            mAlertDialog.show();
            return false;
        } else {
            return true;
        }
    }
}
